package com.efounder.chat.publicnumber;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.core.xml.StubObject;
import com.efounder.chat.R;
import com.efounder.chat.activity.PublicNumerInfoActivity;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.fragment.ChatSenderFragment;
import com.efounder.chat.handler.ChatMessageListener;
import com.efounder.chat.listener.OnTouchListViewListener;
import com.efounder.chat.manager.ChatListManager;
import com.efounder.chat.manager.ChatVoiceRecordAnimManager;
import com.efounder.chat.model.UpdateBadgeViewEvent;
import com.efounder.chat.service.MessageService;
import com.efounder.chat.struct.MessageChildTypeConstant;
import com.efounder.chat.struct.StructFactory;
import com.efounder.chat.widget.ChatListView;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.form.comp.shoppingcar.ShoppingUtils;
import com.efounder.frame.activity.EFTransformFragmentActivity;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.frame.bean.FilterBean;
import com.efounder.frame.utils.Constants;
import com.efounder.frame.xmlparse.EFAppAccountRegistry;
import com.efounder.frame.xmlparse.EFXmlConstants;
import com.efounder.message.db.MessageDBManager;
import com.efounder.message.manager.JFMessageListener;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.message.struct.IMStruct002;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.utils.ResStringUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;
import static com.efounder.frame.utils.NetStateBroadcastReceiver.isNetActive;

/**
 * 应用号聊天fragment
 *
 * @author hudq
 */
@SuppressLint("ClickableViewAccessibility")
public class PublicChatFragment0522 extends BaseFragment implements
        PublicChatSenderFragment.OnVoiceRecordListener, PublicChatSenderFragment
        .OnClickMessageEditTextListener,
        PublicChatSenderFragment.SendMessageCallback, PublicChatOfficialAccountsSenderFragment
        .OnOfficialAccountKyeboardClickListener, MessageService.MessageServiceNetStateListener,
        MessageService.MessageServiceLoginListener, ChatSenderFragment.PreSendMessageCallback {
    public static final String TAG = "PublicChatActivity";
    private PublicChatSenderFragment publicChatSenderFragment;
    private PublicChatOfficialAccountsSenderFragment chatOfficialAccountsSenderFragment;

    /**
     * 从数据库查询过滤后消息的起始位置;
     */
    private int filterMessageStart = 0;
    /**
     * 判断数据库是否还有更多的消息;
     */
    boolean hasMoreFilterMessage = true;


    /**
     * 进入展示过滤消息的时段
     */

    private boolean isFiltering = false;


    /**
     * 每次展示过滤数据的item数量
     */
    private final int FILTER_MESSAGE_COUNT = 8;
    /**
     * 语音容器（语音时显示在中间的麦克风容器）
     **/
    private View recordingContainer;
    /**
     * 麦克风图片
     **/
    private ImageView micImage;
    /**
     * 语音时 “手指上滑，取消发送” 提示
     **/
    private TextView recordingHint;
    /**
     * 聊天ListView
     **/
    private ChatListView chatListView;
    /**
     * 聊天ListView 的 adapter
     **/
    private PublicChatAdapter chatAdapter;
    public PublicChatFragment0522 activityInstance = null;
    /**
     * 聊天对象id
     **/
    private int id;
    private User user;
    /**
     * 下拉加载更多（转圈圈）
     **/
    private ProgressBar loadmorePB;
    // 设置按钮
    private ImageView iv_setting;
    private ImageView iv_setting_group;
    /**
     * 左上角显示的用户名称
     **/
    private TextView toChatUserNickTextView;
    /**
     * 消息管理器
     **/
    private JFMessageManager messageManager;
    /**
     * 消息监听
     **/
    private JFMessageListener messageListener;
    //listview的onTouch监听
    private OnTouchListViewListener onTouchListViewListener;

    private Handler messageHandler = new MessageHandler(this);
    List<IMStruct002> messageList;//消息记录
    int oldCount;

    private View view;
    private ChatListManager chatListManager = new ChatListManager();

    //标记是否触发滚动到最后
    private boolean isScrollLast = false;

    private RefreshChatBroadcastReceive refreshChatBroadcastReceive = new RefreshChatBroadcastReceive();


    /**
     * 用户展示过滤消息的Adapter;
     */
    private PublicChatAdapter filterChatAdapter;
    private List<IMStruct002> filterMessages;
    private String sql;
    private ImageView filterImageView;

    private static class MessageHandler extends Handler {
        private WeakReference<PublicChatFragment0522> weakReference;

        public MessageHandler(PublicChatFragment0522 activity) {
            weakReference = new WeakReference<PublicChatFragment0522>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            PublicChatFragment0522 activity = weakReference.get();
            switch (msg.what) {
                case 1:
                    if (activity != null && activity.chatAdapter != null) {

                        activity.chatAdapter.notifyDataSetChanged();
                        if (activity.chatListView.getLastVisiblePosition() == activity.chatListView.getCount() - 2) {
                            activity.chatListView.setSelection(activity.chatListView.getCount() - 1);
                        } else {
                            Log.i(TAG, "不滚动到最后一条-------");
                        }
                    }
                    break;
                case 11:
                    if (activity != null && activity.chatAdapter != null) {

                        activity.chatAdapter.notifyDataSetChanged();
                        activity.chatListView.setSelection(activity.chatListView.getCount() - 1);
                    }
                    break;
                case 2:
                    activity.chatAdapter.notifyDataSetChanged();
                    activity.chatListView.setSelection(activity.chatListView.getCount());
                    break;
                case 3:
                    Bundle bundle = msg.getData();
                    if (bundle != null && bundle.containsKey("historyMessageCount")) {
                        int historyMessageCount = bundle.getInt("historyMessageCount");
                        activity.chatAdapter.notifyDataSetChanged();
                        activity.chatListView.setSelection(historyMessageCount - 1);
                    }
                    //3.隐藏显示ProgressBar
                    activity.loadmorePB.setVisibility(View.GONE);
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    /**
     * 过滤原则,尽量不动原先的代码
     * 使用单独的listview来存储过滤出来的消息
     * 设置单独的的Adapter,使用完过滤功能后直接给聊天listview设置成之前的adapter即可
     *
     * @param bean
     */


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void executeFilter(FilterBean bean) {

        if (bean.type == 1) {
            initDataForFilterMessage();
            Log.e(TAG, "execute: " + bean.content);
            sql = bean.content + " limit " + filterMessageStart + "," + FILTER_MESSAGE_COUNT + ";";
//            sql = "select * from Message where hex(body) like '%" + bill16 + "%'" + " limit " + filterMessageStart + "," + FILTER_MESSAGE_COUNT + ";";
            List<IMStruct002> result = loadFilterMessage();
            filterMessages.addAll(result);

            if (filterChatAdapter == null) {
                filterChatAdapter = new PublicChatAdapter(getActivity(), chatListView, filterMessages);
            }
            chatListView.setAdapter(filterChatAdapter);

            chatListView.setSelection(filterChatAdapter.getCount() - 1);
        }

    }

    private void initDataForFilterMessage() {


        isFiltering = true;
        filterMessageStart = 0;
        hasMoreFilterMessage = true;
        if (filterMessages == null) {
            filterMessages = new ArrayList<IMStruct002>();

        } else {
            filterMessages.clear();
        }
    }


    /**
     * 将状态调整的正常的状态,即聊天的正常状态
     */
    public void resetStatetoChat() {

        //不再是过滤时态
        isFiltering = false;

        filterMessageStart = 0;
    }


    /**
     * 去数据库加载数据F
     *
     * @return 加载的数据, 如果到最后则返回空
     */
    public List<IMStruct002> loadFilterMessage() {

        if (!hasMoreFilterMessage) {
            return null;
        }
//        MessageDBHelper dbHelper = new MessageDBHelper(AppContext.getCurrentActivity());
//        MessageDBManager dbManager = new MessageDBManager(dbHelper);
        MessageDBManager dbManager = MessageDBManager.getInstance();

        List<IMStruct002> result = dbManager.query(sql);
        if (result.size() < FILTER_MESSAGE_COUNT) {
            hasMoreFilterMessage = false;

        }
        //说明此时数据库可能还有更多的消息

        filterMessageStart += FILTER_MESSAGE_COUNT;

        return result;

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
            savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_public_chat, container, false);
        user = new User();
        id = getActivity().getIntent().getIntExtra("id", 1);
        user = WeChatDBManager.getInstance().getOneUserById(id);

        Log.i(TAG, "onCreate------getIntent()----id:" + id);

        oldCount = JFMessageManager.getInstance().getUnReadCount(id, (byte) 0);
        JFMessageManager.getInstance().unreadZero(id, (byte) 0);

        initAttr();
        initView();
        setUpView();
        Log.i(TAG, "onCreate-------------");
        MessageService.addMessageServiceLoginListener(this);
        MessageService.addMessageServiceNetStateListener(this);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        //！！！启动服务(再onResume中启动，防止这种情况：Activity处于前台，service先于Activity被回收掉)
        getActivity().startService(new Intent(getActivity(), MessageService.class));
        //判断是否显示网络不可用
        if (!isNetActive() || !JFMessageManager.isChannelActived()) {
            toChatUserNickTextView.setText(getActivity().getIntent().getStringExtra("nickName") +
                    ResStringUtil.getString(R.string.wrchatview_network_unavailable));
        }
        if (chatAdapter != null) {
            chatAdapter.notifyDataSetChanged();
            if (isScrollLast) {
                chatListView.setSelection(chatListView.getCount() - 1);
            }
        }

        resumeFilterImageView();

    }

    private void resumeFilterImageView() {

        List<StubObject> stubListByElementName = EFAppAccountRegistry.getStubListByElementName(EFXmlConstants.FILTER_MODULE);
        if (stubListByElementName != null && stubListByElementName.size() > 0) {
            FragmentActivity activity = getActivity();
            if (activity instanceof EFTransformFragmentActivity) {
                filterImageView = ((EFTransformFragmentActivity) activity).getEFTitleView().getFilterImageView();
                if (filterImageView != null) {
                    filterImageView.setVisibility(View.VISIBLE);

                }
            }

        }
    }


    /**
     * 初始化一些属性
     */
    private void initAttr() {
        messageManager = JFMessageManager.getInstance();
        messageListener = new ChatMessageListener(getContext(), id, messageHandler);
        messageManager.addMessageListener(EnvironmentVariable.getProperty(CHAT_USER_ID), messageListener);
    }

    /**
     * initView
     */
    protected void initView() {
        //XXX- 隐藏topBar
        view.findViewById(R.id.top_bar).setVisibility(View.GONE);
        publicChatSenderFragment = (PublicChatSenderFragment) getChildFragmentManager()
                .findFragmentById(R.id.fragment_chat_sender);
        publicChatSenderFragment.setOnClickMessageEditTextListener(this);
        publicChatSenderFragment.setOnVoiceRecordListener(this);
        publicChatSenderFragment.setSendMessageCallback(this);
        publicChatSenderFragment.setPreSendMessageCallback(this);
        onTouchListViewListener = publicChatSenderFragment;
        publicChatSenderFragment.setOnTouchListViewListener(onTouchListViewListener);

        recordingContainer = view.findViewById(R.id.recording_container);
        micImage = (ImageView) view.findViewById(R.id.mic_image);
        recordingHint = (TextView) view.findViewById(R.id.recording_hint);
        chatListView = (ChatListView) view.findViewById(R.id.list);
        loadmorePB = (ProgressBar) view.findViewById(R.id.pb_load_more);
        toChatUserNickTextView = ((TextView) view.findViewById(R.id.name));

        iv_setting = (ImageView) this.view.findViewById(R.id.iv_setting);
        iv_setting_group = (ImageView) this.view.findViewById(R.id.iv_setting_group);


        chatOfficialAccountsSenderFragment = new PublicChatOfficialAccountsSenderFragment();
        chatOfficialAccountsSenderFragment
                .setOnOfficialAccountKyeboardClickListener(this);
        publicChatSenderFragment.setOnOfficialAccountKyeboardClickListener(this);

        iv_setting.setVisibility(View.GONE);
        iv_setting_group.setVisibility(View.VISIBLE);
        iv_setting.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                Intent intent = new Intent(getActivity(), PublicNumerInfoActivity.class);
                intent.putExtra("id", id);
                intent.putExtra("publicchatfragment", "true");
                startActivity(intent);
            }

        });
    }


    @SuppressWarnings("deprecation")
    private void setUpView() {
        activityInstance = this;
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        toChatUserNickTextView.setText(getActivity().getIntent().getStringExtra("nickName"));
        messageList = JFMessageManager.getInstance().getMessageList(id, StructFactory.TO_USER_TYPE_PERSONAL);
        // TODO 获取历史消息
        List<IMStruct002> historyImStruct002s = null;
        int fromUserId = Integer.parseInt(EnvironmentVariable
                .getProperty(Constants.CHAT_USER_ID));
        int toUserId = user.getId();
        if (messageList.size() == 0) {
            historyImStruct002s = messageManager.getPersonalHistoryMessage(fromUserId, toUserId, null, 20, null);
        }

        int unReadCount = JFMessageManager.getInstance().getUnReadCount(id, (byte) 0);
        int tempCount = 0;
        for (int i = messageList.size() - 1; i >= 0; i--) {
            if (messageList.get(i).getFromUserId() != Integer.valueOf(EnvironmentVariable
                    .getProperty(Constants.CHAT_USER_ID))
                    && messageList.get(i).getState() != IMStruct002.MESSAGE_STATE_READ
                    && messageList.get(i).getToUserType() != StructFactory.TO_USER_TYPE_GROUP
                    && messageList.get(i).getReadState() != IMStruct002.MESSAGE_STATE_READ
                    ) {
                JFMessageManager.getInstance().sendReadMessage(messageList.get(i));

            }
        }

        IMStruct002 imStruct002_6 = new IMStruct002();

        String body = "{\"content\":[{\"title\":\"公众号头标题\",\"image\":\"assets://00.png\"," +
                "\"url\":\"http://www.sina.com.cn/\"},{\"title\":\"公共号底部标题\"," +
                "\"image\":\"assets://01.png\",\"url\":\"http://www.163.com/\"}," +
                "{\"title\":\"公共号底部标题\",\"image\":\"assets://02.png\",\"url\":\"http://www.163" +
                ".com/\"}]}";
        imStruct002_6.setTime(System.currentTimeMillis());
        imStruct002_6.setFromUserId(0);
        imStruct002_6.setToUserId(54);
        imStruct002_6.setBody(body.getBytes());
        imStruct002_6.setToUserType(StructFactory.TO_USER_TYPE_OFFICIAL_ACCOUNT);
        byte messagechildType6 = (byte) MessageChildTypeConstant.subtype_officalAccount;
        imStruct002_6.setMessageChildType(messagechildType6);
        imStruct002_6.setState(0);

        setupChatListView();
    }

    private void setupChatListView() {
        chatAdapter = new PublicChatAdapter(getActivity(), chatListView, messageList);
        chatListView.setAdapter(chatAdapter);
        chatListView.setSelection(chatListView.getCount() - 1);
        //Touch监听
        chatListView.setOnTouchListener(new ChatListViewOnTouchListener());
    }


    @Override
    public void sendMessage(IMStruct002 struct002) {
        try {
            if (struct002 != null) {
                // FIXME 测试发送文本
                struct002.setToUserId(id);
                struct002.setFromUserId(Integer.parseInt(EnvironmentVariable.getProperty(Constants.CHAT_USER_ID)));
                Log.i("PublicChatFragment--", EnvironmentVariable.getProperty(Constants.CHAT_USER_ID));
                struct002.setToUserType((byte) 0);
                boolean b = messageManager.sendMessage(struct002);
                Log.i(TAG, "发送 ------ sendMessage:" + struct002.toString());
                chatAdapter.notifyDataSetChanged();
                chatListView.setSelection(chatListView.getCount() - 1);
//                messageHandler.sendEmptyMessage(11);
//                new AsyncTask<IMStruct002, Integer, String>() {
//
//                    @Override
//                    protected String doInBackground(IMStruct002... params) {
//                        try {
//                            IMStruct002 struct002 = params[0];
//                            struct002.setToUserType((byte) 0);
//                            boolean b = messageManager.sendMessage(struct002);
//                            Log.i(TAG, "发送 ------ sendMessage:" + struct002.toString());
//                            //XXX 判断网络是否连接，如果没连接，直接加入未发送队列
//                            //if (!JFMessageManager.isChannelActive) {
//                            //	ChatMessageQueue.unsendMessageList.add(struct002);
//                            //}
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//
//                        return null;
//                    }
//                }.execute(struct002);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void preSendMessage(IMStruct002 struct002) {
        if (struct002 != null) {
            struct002.setToUserId(id);
            struct002.setFromUserId(Integer.parseInt(EnvironmentVariable
                    .getProperty(Constants.CHAT_USER_ID)));
            struct002.putExtra("progress", 0);
            messageManager.preSendMessage(struct002);
            chatAdapter.notifyDataSetChanged();
            chatListView.setSelection(chatListView.getCount() - 1);
        }
    }

    @Override
    public void updateProgress(IMStruct002 struct002, double percent) {
        chatAdapter.notifyDataSetChanged();
    }

    @Override
    public void sendPreMessage(final IMStruct002 struct002) {
        if (struct002 != null) {

            new AsyncTask<IMStruct002, Integer, String>() {

                @Override
                protected String doInBackground(IMStruct002... params) {
                    try {
                        messageManager.sendPreMessage(struct002);
                        Log.i(TAG, "发送 ------ sendPreMessage:" + struct002.toString());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    return null;
                }
            }.execute(struct002);
        }

    }

    @Override
    public void onRecording(int musicalScale) {
        micImage.setImageDrawable(ChatVoiceRecordAnimManager.getMicImages(getActivity())[musicalScale]);
    }

    @Override
    public void onRecorderButtonTouchDown(View v) {
        recordingContainer.setVisibility(View.VISIBLE);
        recordingHint.setText(getString(R.string.move_up_to_cancel));
        recordingHint.setBackgroundColor(Color.TRANSPARENT);
    }

    @Override
    public void onRecorderButtonTouchMove(View v, boolean isCancleRecord) {
        if (isCancleRecord) {
            recordingHint.setText(getString(R.string.release_to_cancel));
            recordingHint
                    .setBackgroundResource(R.drawable.recording_text_hint_bg);
        } else {
            recordingHint.setText(getString(R.string.move_up_to_cancel));
            recordingHint.setBackgroundColor(Color.TRANSPARENT);
        }

    }

    @Override
    public void onRecorderButtonTouchUp(View v) {
        recordingContainer.setVisibility(View.INVISIBLE);
    }

    @Override
    public void onRecorderButtonTouchCancle(View v) {
        recordingContainer.setVisibility(View.INVISIBLE);
    }

    @Override
    public void onClickMessageEditText(View v) {
        chatListView.setSelection(chatListView.getCount() - 1);
    }

    @Override
    public void onOfficialAccountKyeboardClick(View v,
                                               boolean isClickFromOfficialAccountView) {
        FragmentTransaction fragmentTransaction = getChildFragmentManager()
                .beginTransaction();
        if (publicChatSenderFragment.isVisible()) {
            fragmentTransaction.hide(publicChatSenderFragment);
            fragmentTransaction.show(chatOfficialAccountsSenderFragment);
        } else {
            fragmentTransaction.hide(chatOfficialAccountsSenderFragment);
            fragmentTransaction.show(publicChatSenderFragment);
        }
        fragmentTransaction.commit();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i(TAG, TAG + "-----------requestCode:" + requestCode
                + ",resultCode" + resultCode);
    }

    //    @Override
//    public void onNewIntent(Intent intent) {
//        // TODO Auto-generated method stub
//        super.onNewIntent(intent);
//        id = intent.getIntExtra("id", 1);
//        chatType = intent.getByteExtra("chattype",
//                StructFactory.TO_USER_TYPE_OFFICIAL_ACCOUNT);
//        if (chatType == StructFactory.TO_USER_TYPE_OFFICIAL_ACCOUNT) {
//            user = weChatDBManager.getOneFriendById(id);
//            initView();
//            setUpView();
//        }
//    }
    @Subscribe
    public void onOperationMessageEvent(Map<String, Object> event) {
//        event.put("cmd","delete");
//        event.put("position",position);
        String cmd = (String) event.get("cmd");
        if ("delete".equals(cmd)) {
            int position = (int) event.get("position");
            IMStruct002 message = messageList.get(position);
            JFMessageManager.getInstance().removeMessage(message);
        } else if ("scrollLast".equals(cmd)) {
            //刷新界面，滚动到最后一条
            isScrollLast = true;
        }
    }

    @Override
    public void onDestroy() {
        if (messageListener != null) {
            messageManager.removeMessageListener(EnvironmentVariable.getProperty(CHAT_USER_ID), messageListener);
        }
        MessageService.removeMessageServiceLoginListener(this);
        MessageService.removeMessageServiceNetStateListener(this);
        //如果可以，请在chatListManager中统一释放资源
        chatListManager.release(activityInstance);
        EventBus.getDefault().unregister(this);
        activityInstance=null;
        super.onDestroy();
    }


    @Override
    public void onPause() {
        super.onPause();
        hiddenFilterImageView();

        chatListManager.clearunReadCount(id, (byte) 0);
        EventBus.getDefault().post(new UpdateBadgeViewEvent(user.getId() + "", (byte) 2));
    }

    private void hiddenFilterImageView() {
          Log.e(TAG, "onPause:------------ddmj ");
      if(filterImageView!=null){
          Log.e(TAG, "onPause:------------mj ");

          filterImageView.setVisibility(View.GONE);
      }
    }


    @Override
    public void netStateChange(int net_state) {
        Log.i(TAG, "netStateChange--监听网络状态--" + net_state);
        if (net_state == 0) {
            Message message = new Message();
            message.what = 0;
            this.netStateChangeHandler.sendMessage(message);
        } else {
            Message message = new Message();
            message.what = 1;

            this.netStateChangeHandler.sendMessage(message);
        }
    }

    //处理网络监听状态handle
    Handler netStateChangeHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    toChatUserNickTextView.setText(toChatUserNickTextView.getText() + ResStringUtil.getString(R.string.wrchatview_network_unavailable));
                    break;
                case 1:
                    if (getActivity().getIntent() != null)
                        toChatUserNickTextView.setText(getActivity().getIntent().getStringExtra
                                ("nickName"));

                    break;
            }
            super.handleMessage(msg);
        }
    };

    //监听tcp是否可用事件
    @Override
    public void onLoginSuccess() {
        Message message = new Message();
        message.what = 1;

        this.netStateChangeHandler.sendMessage(message);
    }

    @Override
    public void onLoginFail(String errorMsg) {

    }

    @Override
    public void onStart() {
        super.onStart();
        Log.i("---------", "onStart-----------注册刷新聊天列表广播");
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ShoppingUtils.BROADCAST_ACTION_REFRESH_CHAT); //为BroadcastReceiver指定action，即要监听的消息名字。
        getContext().registerReceiver(refreshChatBroadcastReceive, intentFilter); //注册监听
    }

    @Override
    public void onStop() {
        super.onStop();

        Log.i("---------", "onStop-----------取消刷新聊天列表广播");
        getContext().unregisterReceiver(refreshChatBroadcastReceive); //取消监听
    }

    private class RefreshChatBroadcastReceive extends BroadcastReceiver {

        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.i("---------", "BroadcastReceiver-----------接收到广播：action=" + action);
            if (ShoppingUtils.BROADCAST_ACTION_REFRESH_CHAT.equals(action)) { //判断是否接收到广播
                //刷新聊天列表
                chatAdapter.notifyDataSetChanged();
            }
        }
    }


    private class ChatListViewOnTouchListener implements View.OnTouchListener {

        private long chatListViewTouchMoveTime;
        private int chatListViewDownY;
        private int chatListViewDownYSlop;

        public ChatListViewOnTouchListener() {
            chatListViewDownYSlop = (int) (5 * getResources().getDisplayMetrics().density);
        }

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    if (onTouchListViewListener != null)
                        onTouchListViewListener.onTouchListView();
                    chatListViewDownY = (int) event.getY();
                    chatListManager.hideKeyboard(getActivity());
                    break;
                case MotionEvent.ACTION_UP:
                    v.performClick();
                    break;
                case MotionEvent.ACTION_MOVE:
                    //触发下拉事件，每0.5秒执行一次
                    if (event.getY() - chatListViewDownY > chatListViewDownYSlop && System.currentTimeMillis() - chatListViewTouchMoveTime > 500) {
                        Log.e("==", "=====每0.5秒执行一次：" + event.getAction());
                        if (isFiltering) {
                            tryLoadFilterMessage();
                        } else {

                            tryLoadHistoryMessage();

                        }

                        chatListViewTouchMoveTime = System.currentTimeMillis();
                    }
                    break;

                default:
                    break;
            }
            return false;
        }


    }


    /***
     * 分页加载更多的过滤后的消息
     */
    private void tryLoadFilterMessage() {
        if (!hasMoreFilterMessage) {
            //如果没有数据直接返回;
            return;
        }

        View topView = chatListView.getChildAt(0);
        if (chatListView.getFirstVisiblePosition() == 0 && topView != null && topView.getTop() == 0 && loadmorePB.getVisibility() != View.VISIBLE) {
            Log.e("==", "加载更多--onScroll==firstVisibleItem：" + topView.getTop());
            //1.先显示ProgressBar
            loadmorePB.setVisibility(View.VISIBLE);
            new AsyncTask<String, Integer, List<IMStruct002>>() {

                @Override
                protected List<IMStruct002> doInBackground(String... params) {
                    List<IMStruct002> filterImStruct002s = loadFilterMessage();
                    return filterImStruct002s;
                }

                @Override
                protected void onPostExecute(List<IMStruct002> imStruct002s) {
                    super.onPostExecute(imStruct002s);
                    //隐藏进度条
                    loadmorePB.setVisibility(View.GONE);
                    if (imStruct002s == null) {
                        return;
                    }
                    filterMessages.addAll(imStruct002s);
                    filterChatAdapter.notifyDataSetChanged();
                    int count = imStruct002s.size();
                    chatListView.setSelection(count - 1);
                }
            }.executeOnExecutor(Executors.newCachedThreadPool());

        }


    }

    private void tryLoadHistoryMessage() {
        View topView = chatListView.getChildAt(0);
        if (chatListView.getFirstVisiblePosition() == 0 && topView != null && topView.getTop() == 0 && loadmorePB.getVisibility() != View.VISIBLE) {
            Log.e("==", "加载更多--onScroll==firstVisibleItem：" + topView.getTop());
            //1.先显示ProgressBar
            loadmorePB.setVisibility(View.VISIBLE);
            new AsyncTask<String, Integer, List<IMStruct002>>() {

                @Override
                protected List<IMStruct002> doInBackground(String... params) {
                    List<IMStruct002> historyImStruct002s = chatListManager.getHistoryMessage(StructFactory.TO_USER_TYPE_OFFICIAL_ACCOUNT, user, messageManager, null, messageList.get(0).getMessageID(), 20, null);
                    chatListManager.solveUnRead(messageList, historyImStruct002s);
                    return historyImStruct002s;
                }

                @Override
                protected void onPostExecute(List<IMStruct002> imStruct002s) {
                    super.onPostExecute(imStruct002s);
                    chatAdapter.notifyDataSetChanged();
                    int historyMessageCount = imStruct002s.size();
                    chatListView.setSelection(historyMessageCount - 1);
                    //3.隐藏显示ProgressBar
                    loadmorePB.setVisibility(View.GONE);
                }
            }.executeOnExecutor(Executors.newCachedThreadPool());

        }
    }
}
